package kaler.radiovirsa.app;

import java.util.Random;

import kaler.radiovirsa.app.constant.GlobalConfig;
import kaler.radiovirsa.app.util.UtilNetwork;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.Gravity;
import android.widget.TextView;

public class SplashActivity extends MyApp {
	private ProgressDialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.splash_layout);

		if (UtilNetwork.isNetworkConnected(this)) {
			new myAsyncTask().execute();
		} else
			showDialogSetting();
	}

	private class myAsyncTask extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			dialog = ProgressDialog.show(SplashActivity.this, "",
					"Loading..Wait..", true);
			dialog.show();
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			SystemClock.sleep(2000);
			randomWithProbability();
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			Intent intent = new Intent(SplashActivity.this,
					MainActivity.class);
			startActivity(intent);
			dialog.dismiss();
			finish();
			super.onPostExecute(result);
		}
	}

	void showDialogSetting() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		// Creates textview for centre title
		TextView myMsg = new TextView(this);
		myMsg.setText("No internet connection");
		myMsg.setGravity(Gravity.CENTER_HORIZONTAL);
		myMsg.setTextSize(20);
		myMsg.setTextColor(Color.WHITE);
		// set custom title
		builder.setCustomTitle(myMsg);
		builder.setMessage("Please check your setting network");
		builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.dismiss();
			}
		});
		builder.setPositiveButton("Setting",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.dismiss();
						startActivity(new Intent(
								android.provider.Settings.ACTION_SETTINGS));
					}
				});
		AlertDialog dialog = builder.show();
	}
	
	public void randomWithProbability() {
		int min = 0;
		int max = 100;
		Random r = new Random();
		int randValue = r.nextInt(max - min + 1) + min;

		if (randValue >= 0 && randValue <= 79)
			GlobalConfig.idQCCurrent = GlobalConfig.idQC1;
		else if (randValue >= 80 && randValue <= 89)
			GlobalConfig.idQCCurrent = GlobalConfig.idQC2;
		else
			GlobalConfig.idQCCurrent = GlobalConfig.idQC3;
	}
}
